import { useLocalStorage, usePreferredLanguages } from '@vueuse/core'
import type { PostTranslationHandler, VueMessageType } from 'vue-i18n'

import en from '@/i18n/locales/en.json'
import zhCn from '@/i18n/locales/zh-cn.json'

const SUPPORT_LANGUAGES = ['en', 'zh-cn'] as const
type SupportLanguage = (typeof SUPPORT_LANGUAGES)[number]

const preferredLanguages = usePreferredLanguages()

const getPreferredLocale = () => (preferredLanguages.value.find(lang => lang.toLowerCase().startsWith('zh')) ? 'zh-cn' : 'en')

const localeStorage = useLocalStorage<SupportLanguage>('locale', 'en')

const postTranslation: PostTranslationHandler<VueMessageType> = (str, key) => (str === '' ? key : str)

const i18nOptions = {
  legacy: false,
  locale: localeStorage.value,
  fallbackLocale: 'en',
  missingWarn: false,
  fallbackWarn: false,
  messages: {
    en,
    'zh-cn': zhCn
  },
  postTranslation
}

export { i18nOptions, localeStorage, type SupportLanguage }
